<template>
	<view class="popup-overlay" v-if="show">
		<view class="popup">
			<view class="popup-header">
				<text class="title">{{ room.id ? '编辑房间' : '添加房间' }}</text>
				<text class="close-btn" @click.stop="closePopup">×</text>
			</view>
			<view class="popup-content">
				<input class="popup-input" type="text" v-model="room.name" placeholder="输入房间名称" />
				<!-- <text class="title">房间设备ID</text> -->
				<input class="popup-input" type="text" v-model="room.door_device_id" placeholder="房间设备ID" />
				<!-- <text class="title">空调设备Mac</text> -->
				<input class="popup-input" type="text" v-model="room.ai_device_id" placeholder="空调设备Mac" />
				<!-- <text class="title">空调设备Key</text> -->
				<input class="popup-input" type="text" v-model="room.left_ball_id" placeholder="空调设备Key" />
				<!-- <text class="title">网球机Mac</text> -->
				<input class="popup-input" type="text" v-model="room.ball_mac" placeholder="网球机Mac" />

				<view v-for="(row, rowIndex) in inputRows" :key="rowIndex">
				    <view v-for="(item, itemIndex) in row" :key="itemIndex">
				        <text class="title">赛道名称</text>
				        <input class="popup-input" type="text" v-model="item.name" placeholder="赛道名称" />
				    </view>
				</view>

				<text class="title">起订时长</text>
				<view class="popup-input">30 分钟</view>

				<!-- <view class="popup-area">
					<text class="title">添加区域</text>
					<view class="input-row" v-for="(row, rowIndex) in inputRows" :key="rowIndex">
						<view class="input-wrapper" v-for="(input, inputIndex) in row" :key="inputIndex"
							:class="{'last-input': inputIndex === row.length - 1}">
							<input type="text" v-model="input.name" class="input-box" />
							<view class="delete-btn" @click="removeInput(rowIndex, inputIndex)">✖</view>
						</view>
					</view>
					<button @click="addInputRow" class="add-row-btn">添加一行</button>
				</view>
				<picker mode="selector" :range="durationOptions.map(option => option.label)" @change="onDurationChange">
					<view mode="selector">
						<text class="title">起订时长</text>
						<view class="picker-custom">
							<view class="picker-selected">{{ selectedDurationLabel }}</view>
							<view class="picker-arrow"></view>
						</view>
					</view>
				</picker> -->

				<view class="time-slot-container">
					<time-slot :newDatas="roomData.timeprice" :duration="room.duration" :initialPrices="initialPrices"
						@update-price="handlePriceUpdate" />
				</view>
			</view>
			<button class="confirm-button" @click="confirmAddRoom">确认{{ room.id ? '编辑' : '添加' }}</button>
		</view>
	</view>
</template>

<script>
	import timeSlot from './timeSlot.vue';
	export default {
		components: {
			timeSlot
		},
		props: {
			show: Boolean,
			roomData: Object // 接收父组件传递的数据
		},
		data() {
			return {
				initialPrices: [], // 仅在时长变化时更新
				inputRows: [[{name: "01号"}]],
				inputRow: {
					name: '01号'
				},
				room: {
					name: '',
					door_device_id: '',
					ai_device_id: '',
					left_ball_id: '',
					duration: 30
				},
				durationOptions: [{
						label: '30分钟',
						value: 30
					},
					{
						label: '45分钟',
						value: 45
					},
					{
						label: '60分钟',
						value: 60
					},
					{
						label: '90分钟',
						value: 90
					}
				],
				timeSlots: [] // 存储根据起订时长生成的时间段
			};
		},
		mounted() {
			// 初始时不更新 initialPrices，只生成时间段
			this.updateTimeSlots(this.room.duration);
		},
		watch: {
			roomData(newData) {
				if (newData) {
					this.room = {
						...newData
					};
					this.inputRows = this.room.area || [
						[{
							name: '01号'
						}]
					];
					this.updateTimeSlots(this.room.duration); // 根据新的时长更新时间段
					this.newDatas = this.room.timeprice;
					this.initialPrices = this.room.timeprice || [];
				}
			},
			'room.duration': function(newDuration) {
				this.updateTimeSlots(newDuration); // 监听起订时长变化，重新生成时间段
			}
		},
		computed: {
			selectedDurationLabel() {
				const option = this.durationOptions.find(option => option.value == this.room.duration);
				return option ? option.label : '选择起订时长';
			}
		},
		methods: {
			// 根据起订时长更新时间段
			updateTimeSlots(duration) {
				let startTime = 9; // 默认从9:00开始
				let endTime = 22; // 默认到22:00
				let interval = duration; // 使用传入的 duration 来动态设置间隔

				this.timeSlots = [];
				let currentTime = startTime * 60; // 将开始时间转为分钟（9:00为540分钟）

				// 生成时间段
				while (currentTime + interval <= endTime * 60) { // 修正循环条件，确保不会超出结束时间
					let hour = Math.floor(currentTime / 60); // 计算小时
					let minute = currentTime % 60; // 计算分钟
					let formattedTime = `${hour < 10 ? '0' + hour : hour}:${minute < 10 ? '0' + minute : minute}`;
					this.timeSlots.push(formattedTime);
					currentTime += interval; // 增加指定的间隔
				}
			},
			// 更新价格
			handlePriceUpdate(payload) {
				const {
					index,
					price,
					startTime
				} = payload;
				while (this.initialPrices.length <= index) {
					this.initialPrices.push({
						price: '',
						time: ''
					});
				}
				this.initialPrices[index].price = price;
				this.initialPrices[index].time = startTime;
			},
			addInputRow() {
				const newRow = [];
				const currentCount = this.inputRows.flat().length;
				for (let i = 1; i <= 3; i++) {
					const nextNumber = currentCount + i;
					const formattedNumber = nextNumber < 10 ? `0${nextNumber}号` : `${nextNumber}号`;
					newRow.push({
						name: formattedNumber
					});
				}
				this.inputRows.push(newRow);
			},
			removeInput(rowIndex, inputIndex) {
				if (this.inputRows[rowIndex].length === 1 && inputIndex === 0) {
					this.inputRows.splice(rowIndex, 1);
				} else {
					this.inputRows[rowIndex].splice(inputIndex, 1);
				}
			},
			closePopup() {
				this.$emit('close');
			},
			onDurationChange(e) {
				const selectedIndex = e.detail.value;
				this.room.duration = this.durationOptions[selectedIndex].value;
				this.updateTimeSlots(this.room.duration);
			},
			confirmAddRoom() {
				// 检查价格是否为空
				for (let i = 0; i < this.initialPrices.length; i++) {
					if (!this.initialPrices[i].price) {
						uni.showToast({
							title: '价格不能为空',
							icon: 'none'
						});
						return; // 如果有价格为空，阻止继续执行
					}
				}
				const data = {
					name: this.room.name,
					door_device_id: this.room.door_device_id,
					ai_device_id: this.room.ai_device_id,
					left_ball_id: this.room.left_ball_id,
					area: this.inputRows.map(row => row.map(input => ({
						name: input.name
					}))),
					duration: this.room.duration,
					price: this.initialPrices.map(item => item.price),
					timeprice: this.initialPrices,
					isholidayprice: 0,
					status: 'normal',
					ball_mac: this.room.ball_mac,
					id: this.room.id || null
				};
				if (this.room.id) {
					this.editRoom(data);
				} else {
					this.addNewRoom(data);
				}
			},
			addNewRoom(data) {
				// 新增房间
				this.$xyfun.userStoreId().then(store_id => {
					this.$api.post({
						url: '/Venue/Addvenue',
						loadingTip: '加载中...',
						data: {
							store_id: store_id,
							...data
						},
						success: res => {
							uni.showToast({
								title: '添加成功',
								icon: 'success',
								duration: 2000
							});
							this.$emit('refreshData');
							this.closePopup();
						},
						error: err => {
							this.isLoading = false;
						}
					});
				});
			},
			editRoom(data) {
				// 修改房间
				this.$xyfun.userStoreId().then(store_id => {
					this.$api.post({
						url: '/Venue/Editvenue',
						loadingTip: '加载中...',
						data: {
							store_id: store_id,
							room_id: data.id,
							...data
						},
						success: res => {
							this.$emit('refreshData');
							this.closePopup();
						},
						error: err => {
							this.isLoading = false;
						}
					});
				});
			}
		}
	};
</script>


<style scoped>
	.popup-area {
		/* padding: 20px; */
		margin-bottom: 10px;
	}

	.area-number {
		display: inline-block;
		width: 30px;
		text-align: center;
		margin-right: 10px;
		font-weight: bold;
		color: #333;
		line-height: 32px;
		background-color: #f0f0f0;
		border-radius: 5px;
	}

	.input-row {
		display: flex;
		flex-wrap: wrap;
		margin: 10px 0;
	}

	.input-wrapper {
		position: relative;
		flex: 1;
		max-width: calc(33.333% - 20px);
		/* 大约33.33%，减去间距 */
		margin-right: 10px;
		/* 右侧间距 */
		box-sizing: border-box;
		border: 1px solid #ddd;
		border-radius: 5px;
	}

	.input-wrapper.last-input {
		margin-right: 0;
		/* 每行的最后一个输入框没有右侧间距 */
	}

	.input-box {
		width: 100%;
		padding: 10px;
		box-sizing: border-box;
		font-size: 16px;
		min-height: 30px;
		height: auto;
		/* 根据内容自动调整高度 */
		resize: vertical;
	}

	.delete-btn {
		position: absolute;
		top: 0;
		/* 通常使用50%来实现垂直居中，然后通过transform调整 */
		right: -10px;
		/* 根据需要调整位置，确保它在输入框的右上角 */
		transform: translateY(-50%);
		/* 垂直居中 */
		background-color: #ccc;
		/* 灰色背景 */
		border: none;
		border-radius: 50%;
		/* 圆形 */
		width: 16px;
		/* 宽度，根据需要调整 */
		height: 16px;
		/* 高度，与宽度相同以实现圆形 */
		display: flex;
		/* 使用flex布局来居中图标或文本 */
		align-items: center;
		/* 垂直居中 */
		justify-content: center;
		/* 水平居中 */
		font-size: 12px;
		/* 根据需要调整字体大小 */
		color: #fff;
		/* 白色文字，确保在灰色背景上清晰可见 */
		cursor: pointer;
		/* 鼠标悬停时显示为手形 */
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		/* 可选：添加一些阴影以增加立体感 */
	}

	/* 如果您使用的是图标（如Font Awesome），您可能需要调整以下样式 */
	.delete-btn i {
		/* 假设您使用的是<i>标签来包含图标 */
		margin: 0;
		/* 移除任何默认的外边距 */
	}

	.delete-btn:hover,
	.delete-btn:focus {
		color: #c00;
		/* 可选：悬停或聚焦时改变颜色 */
	}

	.add-row-btn {
		margin-top: 10px;
		/* padding: 5px 10px; */
		background-color: #65C61D;
		color: #fff;
		border: none;
		border-radius: 5px;
		cursor: pointer;
	}

	.add-row-btn:hover,
	.add-row-btn:focus {
		background-color: #65C61D;
		/* 可选：悬停或聚焦时改变背景色 */
	}

	.popup-overlay {
		position: fixed;
		top: 50px;
		left: 0;
		width: 100%;
		height: 92%;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		overflow: hidden;
	}

	.time-slot-container {
		max-height: 200px;
		/* 固定高度 */
		overflow-y: auto;
		/* 滚动条 */
		/* border: 1px solid #ccc; */
		/* 可选：边框美化 */
		border-radius: 5px;
		/* padding: 10px; */
		/* background-color: #f9f9f9; */
	}

	.popup {
		background-color: #fff;
		width: 80%;
		border-radius: 10px;
		padding: 20px;
		overflow-y: auto;
		max-height: 90%;
		/* 限制弹窗最大高度 */
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.title {
		font-size: 20px;
		font-weight: bold;
	}

	.close-btn {
		font-size: 24px;
		color: #999;
		cursor: pointer;
	}

	.popup-content {
		display: flex;
		flex-direction: column;
		overflow-y: auto;
		/* 使内容可滚动 */
		flex: 1;
		/* 弹性布局，确保内容区域占据剩余空间 */
		margin-bottom: 20px;
		/* 确保和按钮之间有间距 */
	}

	.popup-input {
		margin-bottom: 15px;
		padding: 10px;
		border: 1px solid #ccc;
		border-radius: 5px;
		background-color: #F5F5F5;
		font-size: 14px;
		/* 调整字体大小 */
	}

	.picker-custom {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 10px;
		border: 1px solid #ccc;
		/* 边框 */
		border-radius: 5px;
		/* 圆角 */
		background-color: #F5F5F5;
		/* 背景颜色 */
		margin-bottom: 15px;
	}

	.picker-selected {
		flex: 1;
		color: #333;
		/* 文字色 */
	}

	.picker-arrow {
		width: 0;
		height: 0;
		border-left: 5px solid transparent;
		border-right: 5px solid transparent;
		border-top: 5px solid #000;
		margin-left: 10px;
	}

	.confirm-button {
		width: 100%;
		/* padding: 10px; */
		background-color: #65C61D;
		color: #fff;
		border: none;
		border-radius: 5px;
		font-size: 16px;
		cursor: pointer;
	}

	.confirm-button:hover {
		background-color: #45a049;
	}
</style>